<?php
//自动生成,请根据需要修改
namespace app\topic\controller;

use app\common\controller\Base;
use function PHPSTORM_META\elementType;
use think\Db;

/**
 * @title 帖子分类页面（模块06-02）
 * @description 帖子分类说明
 * @group 帖子（06）
 * @header name:model_id require:0 default:06-02 desc:模块
 * @groupremark 已使用错误码：1-06-02-0001 校验失败 1-06-02-0002 添加失败 1-06-02-0003 编辑校验失败 1-06-02-0004 编辑失败 1-06-02-0005 获取详情失败  1-06-02-0006 获取列表失败 1-06-02-0007获取单个详情失败 1-06-02-0008 删除失败
 */
class TopicCategory extends Base
{
    //测试
    public function test()
    {
        return 'test 111';
    }

    /**
     * @title 添加帖子分类
     * @description 添加帖子分类
     * @author 李锐志
     * @url /topic/topic_category/add
     * @method *
     *
     * @header name:token require:1 default: desc:token
     *
     * @param name:name type:varchar require:0 other: desc:分类名
     * @param name:parent_id type:int require:0 other: desc:父类id
     * @param name:status type:tinyint require:0 other: desc:状态
     * @param name:create_time type:int require:0 other: desc:创建时间
     * @return data:帖子分类@!
     * @data    id:id    name:分类名    parent_id:父类id    status:状态    create_time:创建时间
     * @return error_id:1-06-02-0001 校验失败  1-06-02-0002 添加失败
     */
    public function add()
    {
        $data = input();
        /**
         *$validate = new \app\topic\validate\TopicCategory();
         *$validate->scene('add');
         *$result = $validate->batch(true)->check($data);
         *if ($result !== true) {
         *$msg['msg']='校验失败';
         *$msg['validate']=$validate->getError();
         *$msg['error_id']='1-06-02-0001';
         *return $this->errorJson($msg);
         *}
         **/
        $model = new \app\topic\model\TopicCategory();
        $flag = $model->save($data);
        if ($flag) {
            $msg['msg'] = '添加成功';
            $msg['data'] = $model->get($model['id']);
            return $this->successJson($msg);
        } else {
            $msg['error_id'] = '1-06-02-0002';
            $msg['msg'] = '添加失败';
            return $this->errorJson($msg);
        }
    }

    /**
     * @title 编辑帖子分类
     * @description 编辑帖子分类
     * @author 李锐志
     * @url /topic/topic_category/edit
     * @method *
     *
     * @header name:token require:1 default: desc:token
     *
     * @param name:id type:int require:0 other: desc:id
     * @param name:name type:varchar require:0 other: desc:分类名
     * @param name:parent_id type:int require:0 other: desc:父类id
     * @param name:status type:tinyint require:0 other: desc:状态
     * @param name:create_time type:int require:0 other: desc:创建时间
     * @return data:帖子分类@!
     * @data    id:id    name:分类名    parent_id:父类id    status:状态    create_time:创建时间
     * @return error_id:1-06-02-0003 校验失败 1-06-02-0004 修改失败
     */
    public function edit()
    {
        $data = input();
        $validate = new \app\topic\validate\TopicCategory();
        $validate->scene('edit');
        $result = $validate->batch(true)->check($data);
        if ($result !== true) {
            $msg['msg'] = '校验失败';
            $msg['validate'] = $validate->getError();
            $msg['error_id'] = '1-06-02-0003';
            return $this->errorJson($msg);
        }
        $model = new \app\topic\model\TopicCategory();
        $flag = $model->edit($data);
        if ($flag !== false) {
            $msg['msg'] = '修改成功';
            $msg['data'] = $model->get($data['id']);
            return $this->successJson($msg);
        } else {
            $msg['error_id'] = '1-06-02-0004';
            $msg['msg'] = '修改失败';
            return $this->errorJson($msg);
        }
    }

    /**
     * @title 删除帖子分类
     * @description 删除帖子分类
     * @author 李锐志
     * @url /topic/topic_category/delete
     * @method *
     *
     * @param name:token require:1 default: desc:token
     *
     * @param name:id type:int|array require:1 other: desc:要删除的id
     * @return error_id:1-06-02-0008 删除失败
     */
    public function delete()
    {
        $id = input('id');
        $model = new \app\topic\model\TopicCategory();
        $flag = $model->destroy($id);
        if ($flag) {
            $msg['msg'] = '删除成功';
            return $this->successJson($msg);
        } else {
            $msg['msg'] = '删除失败';
            $msg['error_id'] = '1-06-02-0008';
            return $this->errorJson($msg);
        }
    }

    /**
     * @title 单个查询帖子分类
     * @description 单个查询帖子分类
     * @author 李锐志
     * @url /topic/topic_category/info
     * @method *
     *
     * @param name:token require:1 default: desc:token
     *
     * @param name:id type:int require:0 other: desc:id
     * @param name:name type:varchar require:0 other: desc:分类名
     * @param name:parent_id type:int require:0 other: desc:父类id
     * @param name:status type:tinyint require:0 other: desc:状态
     * @param name:create_time type:int require:0 other: desc:创建时间
     * @return data:帖子分类@!
     * @data    id:id    name:分类名    parent_id:父类id    status:状态    create_time:创建时间
     * @return error_id:1-06-02-0005 校验失败 1-06-02-0007 获取失败
     */
    public function info()
    {
        $model = new \app\topic\model\TopicCategory();
        $Fields = $model->getTableFields();
        $data = \think\facade\Request::only($Fields);
        /**
         *$validate = new \app\topic\validate\TopicCategory();
         *$validate->scene('info');
         *$result = $validate->batch(true)->check($data);
         */
        if (!$data) {
            $msg['msg'] = '必须有参数';
            $msg['error_id'] = '1-06-02-0005';
            return $this->errorJson($msg);
        }
        $model = new \app\topic\model\TopicCategory();
        $info = $model->where($data)->find();
        if ($info) {
            $msg['msg'] = '获取成功';
            $msg['data'] = $info;
            return $this->successJson($msg);
        } else {

            $msg['msg'] = '获取失败';
            $msg['error_id'] = '1-06-02-0007';
            return $this->errorJson($msg);
        }
    }

    /**
     * @title 查询列表帖子分类
     * @description 查询列表帖子分类
     * @author 宋晓文
     * @url /topic/topic_category/get_list
     * @method *
     * @param name:token require:1 default: desc:token
     * @return list:帖子分类@
     * @list    id:id    name:分类名    parent_id:父类id    status:状态    create_time:创建时间
     */
    public function get_list()
    {
        $model = new \app\topic\model\TopicCategory();
        $Fields = $model->getTableFields();
        $data = \think\facade\Request::only($Fields);

        $where = array();
        foreach ($data as $k => $v) {
            if ($v === 0) {
                continue;
            }
            if ($v == null) {
                unset($data[$k]);
            }
        }
        foreach ($data as $k => $v) {
            if ($k === 'id' || $k === 'parent_id' || $k === 'status') {
                array_push($where, [$k, '=', $data[$k]]);
                continue;
            }
            if (isset($data[$k]) && $data[$k] && !empty($data[$k])) {
                array_push($where, [$k, 'like', "%{$data[$k]}%"]);
            }
        }

        $list = $model->where($where)->order('parent_id', 'asc')->select();

        if (count($list) > 0) {
            $res = $this->genTree($list, $list[0]['parent_id']);
        } else {
            $res = array();
        }

        $msg['list']['data'] = $res;
        return $this->successJson($msg);
    }

    /**
     * 将数据格式化成树形结构
     * @author 宋晓文
     * @param array $items
     * @return array
     */
    function genTree($data, $parent_id = 0)
    {
        $tree = array();
        foreach ($data as $k => $v) {
            if ($v['parent_id'] == $parent_id) {        //父亲找到儿子
                $v['children'] = $this->genTree($data, $v['id']);
                $tree[] = $v;
            }
        }
        return $tree;
    }


    /**
     * @title 前台首页帖子分类
     * @description 前台首页帖子分类
     * @author 李锐志
     * @url /topic/topic_category/homepage_topic_category
     * @method *
     */
    public function homepage_topic_category()
    {
        $category = Db::name('topic_category')
            ->where('parent_id', 0)
            ->where('status', 1)
            ->select();

        foreach ($category as $k => $v) {
            $son_category = Db::name('topic_category')
                ->where('parent_id', $v['id'])
                ->where('status', 1)
                ->column('id');

            if (!empty($son_category)) {
                $category[$k]['topic'] = Db::name('topic')
                    ->where('category_id', 'in', $son_category)
                    ->order('update_time', 'desc')
                    ->limit(8)
                    ->select();

                // 在这里插入帖子: 把浏览量+评论量最高的两个帖子放在最前面
                $top_topic = Db::name('topic')
                    ->where('category_id', 'in', $son_category)
                    ->order(['view_num' => 'desc', 'discuss_num' => 'desc'])
                    ->limit(2)
                    ->select();

//                $top_topic_count = count($top_topic) - 1;
//
//                if ($top_topic_count > 1) {
//                    for ($i = 1; $i >= 0; $i--) {
//                        array_unshift($category[$k]['topic'], $top_topic[$i]);
//                    }
//                } else {
//                    for ($i = $top_topic_count; $i >= 0; $i--) {
//                        array_unshift($category[$k]['topic'], $top_topic[$i]);
//                    }
//                }

                for ($i = 1; $i >= 0; $i--) {
                    array_unshift($category[$k]['topic'], $top_topic[$i]);
                }

                $category[$k]['topic'] = $this->array_unique_fb($category[$k]['topic']);

                $category[$k]['topic'] = array_values($category[$k]['topic']);

                foreach ($category[$k]['topic'] as $key => $value) {
                    if (empty($value['user_id'])) {
                        $category[$k]['topic'][$key]['nickname'] = '';
                    } else {
                        $category[$k]['topic'][$key]['nickname'] = Db::table('zb_user.tp_user')->find($category[$k]['topic'][$key]['user_id'])['nickname'];
                    }
                }

            } else {
                $category[$k]['topic'] = Db::name('topic')
                    ->where('category_id', $v['id'])
                    ->order('update_time', 'desc')
                    ->limit(8)
                    ->select();

                // 在这里插入帖子: 把浏览量+评论量最高的两个帖子放在最前面
                $top_topic = Db::name('topic')
                    ->where('category_id', $v['id'])
                    ->order(['view_num' => 'desc', 'discuss_num' => 'desc'])
                    ->limit(2)
                    ->select();

                for ($i = 1; $i >= 0; $i--) {
                    array_unshift($category[$k]['topic'], $top_topic[$i]);
                }

                $category[$k]['topic'] = $this->array_unique_fb($category[$k]['topic']);

                $category[$k]['topic'] = array_values($category[$k]['topic']);

                foreach ($category[$k]['topic'] as $key => $value) {
                    $category[$k]['topic'][$key]['user'] = get_curl('user', '/user/get_user_information', ['id' => $value['user_id']])['data'];

                    if (empty($value['user_id'])) {
                        $category[$k]['topic'][$key]['nickname'] = '';
                    } else {
                        $category[$k]['topic'][$key]['nickname'] = Db::table('zb_user.tp_user')->find($category[$k]['topic'][$key]['user_id'])['nickname'];
                    }
                }
            }
        }

        $msg['msg'] = '首页分类获取成功';
        $msg['list'] = $category;
        return $this->successJson($msg);
    }

    public function array_unique_fb($array2D)
    {
        foreach ($array2D as $key => $v) {
            $v = implode("x*x", $v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
            $temp[] = $v;
        }

        $temp = array_unique($temp);//去掉重复的字符串,也就是重复的一维数组

        //return $temp;
        foreach ($temp as $k => $v) {
            $tems = explode('x*x', $v);

            $key_name = array('id', 'title', 'is_new', 'view_num', 'discuss_num', 'user_id', 'create_time', 'update_time', 'img_url', 'content', 'category_id', 'topic_type', 'is_mentality', 'main_img_url', 'annotation');
            // 现在开始替换
            $arr_new = array_combine($key_name, $tems);
            //dump($arr_new);
            $temp[$k] = $arr_new;
        }
        return $temp;
    }

    /**
     * @title 前台首页帖子分类更多接口
     * @description 前台首页帖子分类更多接口
     * @author 李锐志
     * @url /topic/topic_category/homepage_topic_category_more
     * @param name:id require:1 default: desc:分类id
     * @method *
     */
    public function homepage_topic_category_more()
    {
        $id = input('id');

        $category = Db::name('topic_category')
            ->where('status', 1)
            ->where('id', $id)
            ->find();
        if (!$category) {
            $msg['msg'] = '该分类不存在或已被禁用!';
            return $this->errorJson($msg);
        }

        $son_category = Db::name('topic_category')
            ->where('parent_id', $id)
            ->where('status', 1)
            ->select();

        foreach ($son_category as $k => $v) {
            $son_category[$k]['topic'] = Db::name('topic')
                ->where('category_id', $v['id'])
                ->order('update_time', 'desc')
                ->limit(7)
                ->select();
        }

        $category['son_category'] = $son_category;
        $msg['msg'] = '获取成功';
        $msg['data'] = $category;
        return $this->successJson($msg);
    }

    /**
     * @title 前台帖子子分类更多接口
     * @description 前台帖子子分类更多接口
     * @author 李锐志
     * @url /topic/topic_category/topic_category_more
     * @param name:id require:1 default: desc:分类id
     * @param name:page require:1 default: desc:第几页
     * @param name:pagesize require:1 default: desc:每页数
     * @method *
     */
    public function topic_category_more()
    {
        $id = input('id');
        $result = Db::name('topic')
            ->where('category_id', $id)
            ->order('update_time', 'desc')
            ->paginate();
        $result = $result->toArray();

        foreach ($result['data'] as $k => $v) {
            $result['data'][$k]['user'] = get_curl('user', 'user/get_user_information', ['id' => $v['user_id']])['data'];
        }

        $msg['msg'] = '获取成功';
        $msg['list'] = $result;
        return $this->successJson($msg);
    }

    /**
     * @title 查询贴子分类列表
     * @description 查询贴子分类列表
     * @author 宋晓文
     * @url /topic/topic_category/get_topic_category_list
     * @method *
     * @return list:分类@
     * @list    id:id      name:分类名
     */
    public function get_topic_category_list()
    {
        $SheJiBoYi = Db::name('topic_category')->field('id,name')->where('name', '设计博弈')->find();
        $id = input('id');
        if (!$id) {
            $id = 0;
        }
        if ($id == 0) {
            $result = Db::name('topic_category')->field('id,name')->where('status', 1)->select();
        } elseif ($id = 1) {
            $where = array(
                array('status', '=', '1'),
                array('parent_id', '=', '0'),
            );
            $result = Db::name('topic_category')->field('id,name')->where($where)->select();
        } elseif ($id = 2) {
            $where = array(
                array('id', '<>', $SheJiBoYi['id']),
                array('parent_id', '<>', $SheJiBoYi['id']),
                array('status', '=', '1'),
            );
            $result = Db::name('topic_category')->field('id,name')->where($where)->select();
        } elseif ($id = 3) {
            $where = array(
                array('id', '=', $SheJiBoYi['id']),
                array('parent_id', '=', $SheJiBoYi['id']),
                array('status', '=', '1'),
            );
            $result = Db::name('topic_category')->field('id,name')->where($where)->select();
        }
        $msg['msg'] = '获取成功';
        $msg['list'] = $result;
        return $this->successJson($msg);
    }

}
